package com.tange.ai.core.sample.share

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.core.sample.R
import com.tange.ai.core.sample.databinding.ActivityDeviceShareBinding
import com.tange.ai.core.sample.utils.Utils
import com.tange.base.toolkit.ClipboardUtils
import com.tange.base.toolkit.Tips
import com.tange.base.toolkit.gone
import com.tange.base.toolkit.visible
import com.tange.core.sharing.DeviceSharing
import com.tange.core.sharing.ShareInfo

class DeviceShareActivity: AppCompatActivity() {

    companion object {
        const val TAG = "DeviceShareActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, DeviceShareActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private lateinit var binding: ActivityDeviceShareBinding

    private var listAdapter: ListAdapter? = null

    private lateinit var deviceId: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)

        binding = ActivityDeviceShareBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
        }

        Utils.setStatusBar(this, Color.TRANSPARENT)

        binding.createShareCode.setOnClickListener {
            DeviceSharing.createCode(deviceId) {
                if (it.success) {
                    binding.shareCodeEditText.setText(it.data)
                    ClipboardUtils.copyToClipboard(this@DeviceShareActivity, it.data)
                    Tips.show("生成成功，已自动复制到剪切板\n请参考文档，将分享码提供给其他人")
                } else {
                    Tips.show("生成失败：${it.code} ${it.message}")
                    binding.shareCodeEditText.setText("")
                }
            }
        }

        listAdapter = ListAdapter(deviceId)
        binding.shareList.adapter = listAdapter
        binding.shareList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)


        queryShareInfo()
    }

    private fun queryShareInfo() {
        DeviceSharing.queryShareInfo(deviceId) {
            if (it.success) {
                if ((it.data?.size ?: 0) > 0) {
                    listAdapter?.refresh(it.data!!)
                } else {
                    binding.emptyView.visible()
                }
            } else {
                binding.emptyView.visible()
                binding.emptyView.text = "查询失败：${it.code} ${it.message}"
            }
        }
    }

    inner class ListAdapter(val deviceId: String) : RecyclerView.Adapter<WiFiViewHolder>() {

        private val dataList: MutableList<ShareInfo> = ArrayList()

        fun refresh(list: List<ShareInfo>?) {
            dataList.clear()
            list?.let { dataList.addAll(it) }
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): WiFiViewHolder {
            val view: View = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_share_list, viewGroup, false)
            return WiFiViewHolder(view)
        }

        override fun onBindViewHolder(viewHolder: WiFiViewHolder, position: Int) {
            val shareInfo = dataList[position]

            if (shareInfo.shareType == ShareInfo.TYPE_PRE_SHARE || shareInfo.shareType == ShareInfo.TYPE_SHARED) {
                if (!TextUtils.isEmpty(shareInfo.nickName)) {
                    viewHolder.title.text = "已分享给 ${shareInfo.nickName}"
                } else {
                    viewHolder.title.text = "已分享给 ${shareInfo.userId}"
                }
                viewHolder.agree.gone()
                viewHolder.reject.gone()
                viewHolder.remove.visible()
                viewHolder.remove.setOnClickListener {
                    DeviceSharing.removeShared(deviceId, shareInfo.shareId!!, shareInfo.shareType!!) {
                        if (it.success) {
                            Tips.show("取消分享成功")
                            queryShareInfo()
                        } else {
                            Tips.show("取消分享失败：${it.code} ${it.message}")
                        }
                    }
                }
            } else {
                if (!TextUtils.isEmpty(shareInfo.nickName)) {
                    viewHolder.title.text = "用户 ${shareInfo.nickName} 请求分享"
                } else {
                    viewHolder.title.text = "用户 ${shareInfo.userId} 请求分享"
                }

                viewHolder.agree.visible()
                viewHolder.reject.visible()
                viewHolder.remove.gone()

                viewHolder.agree.setOnClickListener {
                    DeviceSharing.acceptRequest(shareInfo.shareId!!) {
                        if (it.success) {
                            Tips.show("成功")
                            queryShareInfo()
                        } else {
                            Tips.show("同意分享失败：${it.code} ${it.message}")
                        }
                    }
                }

                viewHolder.reject.setOnClickListener {
                    DeviceSharing.rejectRequest(shareInfo.shareId!!) {
                        if (it.success) {
                            Tips.show("拒绝成功")
                            queryShareInfo()
                        } else {
                            Tips.show("拒绝分享失败：${it.code} ${it.message}")
                        }
                    }
                }
            }

            viewHolder.time.text = "${shareInfo.shareTime}"
        }

        override fun getItemCount(): Int {
            return dataList.size
        }
    }

    class WiFiViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        val icon: ImageView
        val title: TextView
        val time: TextView
        val agree: TextView
        val reject: TextView
        val remove: TextView

        init {
            icon = view.findViewById(R.id.category_icon)
            title = view.findViewById(R.id.name)
            time = view.findViewById(R.id.time)
            agree = view.findViewById(R.id.agree)
            reject = view.findViewById(R.id.reject)
            remove = view.findViewById(R.id.remove)
        }
    }
}

